#include "server.h"

int salt(char *saltnum){
    srand(time(NULL));
    printf("salt begin\n");
    saltnum[0] = '$';
    saltnum[1] = '6';
    saltnum[2] = '$';
    //随机生成中间16位
    const char char16[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    
    for(int i = 0;i < 16;i++){
        saltnum[3+i] = char16[rand()%(sizeof(char16)-1)];
    }
    saltnum[19] = '$';
    printf("salt end\n");
    
    return 0; 
}

int registration(user_t tmpuser, MYSQL *mysql){
    //获取盐值
    char saltnum[128] = {0};
    salt(saltnum);
    //加密
    puts(saltnum);    
    char* saltresult = crypt(tmpuser.passwd,saltnum);
    
    memcpy(tmpuser.passwd,saltresult,20);
    puts(saltresult);
    //先查询用户名是否重复，不能申请已注册的用户名
    char sql[2048] = {0};
    sprintf(sql,"select username from user where username = '%s';",tmpuser.userName);
    int qret = mysql_query(mysql,sql);
    if(qret!=0){
        fprintf(stderr,"mysql_query:%s\n",mysql_error(mysql));
        return -1;
    }
    MYSQL_RES* result = mysql_store_result(mysql);
    MYSQL_ROW row;
    if((row = mysql_fetch_row(result))!=NULL){
        fprintf(stderr,"userName has exited!\n");
        return 0;
    }
    
    //注册，添加新用户
    memset(sql,0,sizeof(sql));
    sprintf(sql,"insert into user (username,salt,passwd,tomb) values ('%s','%s','%s',0);",tmpuser.userName,saltnum,saltresult);
    qret = mysql_query(mysql,sql);
    if(qret!=0){
        fprintf(stderr,"mysql_query:%s\n",mysql_error(mysql));
        return -1;
    }
    
    return 1;
}                                                                               



int loading(user_t tmpuser, MYSQL *mysql) {

    char sql[2048] = {0};
    sprintf(sql,"select salt, passwd, tomb from user where username = '%s';",tmpuser.userName);
    int qret = mysql_query(mysql,sql);
    if(qret!=0){
        fprintf(stderr,"mysql_query:%s\n",mysql_error(mysql));
        //strcmp的结果是1，0，-1，-999代表用户名错误
        return -1;
    }

    //将找到的密码读取出来，如果没有找到，则说明用户名不正确
    //或者用户并未注册
    MYSQL_RES* result = mysql_store_result(mysql);
    MYSQL_ROW row;
    row = mysql_fetch_row(result);
    
    if (!row) {
        return -999;
    }

    if(row[1]!=NULL){
        if(row[2][0] == '0'){
            char* salt_result = crypt(tmpuser.passwd,row[0]);
            char* compare = row[1];
            return strcmp(compare,salt_result);
               
        }else{
            fprintf(stderr,"用户已注销！\n");
            return -999;
        }
    }else{
        return -999;
    }
    return 0;
}
